﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using School.Entities;
using School.Common;
using System.Data.Entity;
using School.Admission;
using School.Organization;



namespace School.Pages.Admission
{
    public partial class StudentTransactionSearch : System.Web.UI.Page
    {
        //***************** This is function to handle page when page load ***************************
        //-**********************************************************************




        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1015) == true)
                {
                    if (!(Page.IsPostBack))
                    {


                        Fillcrls();

                        InitializeControls();

                        GridDataBind();

                    }
                }
                else
                    Response.Redirect("../Default.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }
        # region "Collect Data"

        //***************** This is function to bind data grid  ***************************
        //-**************************************************************************
        protected void GridDataBind()
        {


            Int32 mycount;
            Hashtable SearchTable = new Hashtable();


            SearchTable.Add("Status_Id", "4");

            if (txtSearchFileNumber.Text.Length > 0)
            {
                SearchTable.Add("FileNumber", txtSearchFileNumber.Text.ToString());
            }
            if (ddlSearchcampus_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Campus_Id", ddlSearchcampus_Id.SelectedIndex.ToString());
            }

            if (ddlSearchCertificate_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Certificate_Id", ddlSearchCertificate_Id.SelectedIndex.ToString());
            }
            if (ddlSearchStage_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Stage_Id", ddlSearchCertificate_Id.SelectedIndex.ToString());
            }
            if (ddlSearchGrade_ID.SelectedIndex > 0)
            {
                SearchTable.Add("Grade_ID", ddlSearchCertificate_Id.SelectedIndex.ToString());
            }
            if (ddlSearchNationality_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Nationality_Id", ddlSearchNationality_Id.SelectedIndex.ToString());
            }
            if (ddlFQualification_Id.SelectedIndex > 0)
            {
                SearchTable.Add("Qualification_Id", ddlFQualification_Id.SelectedIndex.ToString());
            }
            if (ddlFCareer.SelectedIndex > 0)
            {
                SearchTable.Add("Career_Id", ddlFCareer.SelectedIndex.ToString());
            }
            if (txtFSpecialization.Text.Length > 0)
            {
                SearchTable.Add("Specialization", txtFSpecialization.Text.ToString());
            }
            if (txtFPointOfGraduation.Text.Length > 0)
            {
                SearchTable.Add("PointOfGraduation", txtFPointOfGraduation.Text.ToString());
            }
            if (txtStreetName.Text.Length > 0)
            {
                SearchTable.Add("StreetName", txtStreetName.Text.ToString());
            }
            if (ddlDistrict_Id.SelectedIndex > 0)
            {
                SearchTable.Add("District_Id", ddlDistrict_Id.SelectedIndex.ToString());
            }
            if (txtSearchRegistrationNumber.Text.Length > 0)
            {
                SearchTable.Add("RegistrationNumber", txtSearchRegistrationNumber.Text.ToString());
            }
            if (txtSearchName.Text.Length > 0)
            {
                switch (rblSearchType.SelectedIndex)
                {
                    case 0:
                        SearchTable.Add("SD_FullName", txtSearchName.Text.ToString() + "%");
                        break;
                    case 1:
                        SearchTable.Add("SD_FullName", "%" + txtSearchName.Text.ToString() + "%");
                        break;
                    case 2:
                        SearchTable.Add("SD_FullName", txtSearchName.Text.ToString());
                        break;
                }
            }
            String RelTab = "";
            String RelTabDef = "";
            if (rblRelatives.SelectedIndex >= 0)
            {
                switch (rblRelatives.SelectedIndex)
                {
                    case 0:
                        RelTab = "SD_Father";
                        RelTabDef = "Father";
                        break;
                    case 1:
                        RelTab = "SD_Mother";
                        RelTabDef = "";
                        break;
                    case 2:
                        RelTab = "SD_Custody";
                        RelTabDef = "Custody";
                        break;
                }
            }

            if (txtRelativeName.Text.Length > 0)
            {
                switch (rblSearchType0.SelectedIndex)
                {
                    case 0:
                        SearchTable.Add("Relative_FullName", txtRelativeName.Text.ToString() + "%");
                        break;
                    case 1:
                        SearchTable.Add("Relative_FullName", "%" + txtRelativeName.Text.ToString() + "%");
                        break;
                    case 2:
                        SearchTable.Add("Relative_FullName", txtRelativeName.Text.ToString());
                        break;
                }
            }
            if (ddlParentsSocialStatus_Id.SelectedIndex > 0)
            {
                SearchTable.Add("ParentsSocialStatus_Id", ddlParentsSocialStatus_Id.SelectedIndex.ToString());
            }
            if (ddlCustodyType_Id.SelectedIndex > 0)
            {
                SearchTable.Add("CustodyType_Id", ddlCustodyType_Id.SelectedIndex.ToString());
            }
            if (ddlStudentLivingPlace_Id.SelectedIndex > 0)
            {
                SearchTable.Add("StudentLivingPlace_Id", ddlStudentLivingPlace_Id.SelectedIndex.ToString());
            }
            //     griddata.DataSource = Student.Mysearch(SearchTable, RelTab, RelTabDef).Select(x => new { x.Id, x.FileNumber, x.Ar_FirstName, x.Ar_SecondName, x.Ar_ThirdNmae, x.Ar_FourthName, x.Gregorian_BirthDate, x.Campus_Id, Certificate = x.ORG_Certificate.Name, Stage = x.ORG_Stage.Name, Grade = x.ORG_Grade.Name, x.Certificate_Id, x.Stage_Id, x.Grade_ID, x.Gender_Id });
            griddata.DataSource = Student.Mysearch(SearchTable, RelTab, RelTabDef);

            griddata.DataBind();
            griddata.Visible = true;
            mycount = griddata.Rows.Count;
            lblRecordNo.Text = "عدد كل الطلاب بالتنسيق = " + mycount.ToString();
            if (mycount == 0)
            {
                lblMessage.Text = "No search result(s) found, please try again.";
            }
            else
            {
                lblMessage.Text = "";
            }


        }

        # endregion


        # region "Fill all crls"

        //***************** This is function to fill crl  ***************************
        //-**************************************************************************

        protected void Fillcrls()
        {
            ddlSearchcampus_Id.DataSource = School.Common.Structure.GetCampuses();
            ddlSearchcampus_Id.DataTextField = "Name";
            ddlSearchcampus_Id.DataValueField = "Id";
            ddlSearchcampus_Id.DataBind();
            ddlSearchcampus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));


            ddlFQualification_Id.DataSource = LookUps.Qualifications();
            ddlFQualification_Id.DataTextField = "Name";
            ddlFQualification_Id.DataValueField = "Id";
            ddlFQualification_Id.DataBind();
            ddlFQualification_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlFCareer.DataSource = LookUps.Jobs();
            ddlFCareer.DataTextField = "Name";
            ddlFCareer.DataValueField = "Id";
            ddlFCareer.DataBind();
            ddlFCareer.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlDistrict_Id.DataSource = LookUps.Districts();
            ddlDistrict_Id.DataTextField = "Name";
            ddlDistrict_Id.DataValueField = "Id";
            ddlDistrict_Id.DataBind();
            ddlDistrict_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlSearchNationality_Id.DataSource = LookUps.Countries();
            ddlSearchNationality_Id.DataTextField = "Name";
            ddlSearchNationality_Id.DataValueField = "Id";
            ddlSearchNationality_Id.DataBind();
            ddlSearchNationality_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlParentsSocialStatus_Id.DataSource = LookUps.ParentsSocialStatus();
            ddlParentsSocialStatus_Id.DataTextField = "Name";
            ddlParentsSocialStatus_Id.DataValueField = "Id";
            ddlParentsSocialStatus_Id.DataBind();
            ddlParentsSocialStatus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlCustodyType_Id.DataSource = LookUps.CustodyType();
            ddlCustodyType_Id.DataTextField = "Name";
            ddlCustodyType_Id.DataValueField = "Id";
            ddlCustodyType_Id.DataBind();
            ddlCustodyType_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlStudentLivingPlace_Id.DataSource = LookUps.LivingWith();
            ddlStudentLivingPlace_Id.DataTextField = "Name";
            ddlStudentLivingPlace_Id.DataValueField = "Id";
            ddlStudentLivingPlace_Id.DataBind();
            ddlStudentLivingPlace_Id.Items.Insert(0, new ListItem("اختيار", "-1"));



        }


        //***************** This is function to initlaize crl  ***************************
        //-**************************************************************************
        protected void InitializeControls()
        {
            txtSearchFileNumber.Text = "";
            txtSearchRegistrationNumber.Text = "";
        }
        protected void InitializeRelControls()
        {
            txtRelativeName.Text = "";
            ddlSearchNationality_Id.SelectedIndex = 0;
            ddlStudentLivingPlace_Id.SelectedIndex = 0;
            ddlParentsSocialStatus_Id.SelectedIndex = 0;
            ddlFQualification_Id.SelectedIndex = 0;
            ddlSearchNationality_Id.SelectedIndex = 0;
            ddlCustodyType_Id.SelectedIndex = 0;
            txtFSpecialization.Text = "";
            txtCRelationToStudent.Text = "";
            txtFCompanyName.Text = "";
            txtFPointOfGraduation.Text = "";
            txtStreetName.Text = "";
        }
        # endregion


        # region "Mode Handlers"

        //***************** This is function to handle page in add mode  ***************************
        //-**************************************************************************
        protected void PutFormInAddMode()
        {
            //txtFirstName.Text = "";
            //txtSecondName.Text = "";
            //txtThirdName.Text = "";
            //txtFourthName.Text = "";
        }


        //***************** This is function to handle page in brows mode  ***************************
        //-**************************************************************************

        protected void PutFormInBrwosMode()
        {
            pnlbrows.Visible = false;

        }

        #endregion


        # region "Grid Events ***********"

        //***************** This is function to handle page when Page Index Changing   ***************************
        //-**************************************************************************
        //***************** This is function to handle page when Page Index Changing   ***************************
        //-**************************************************************************
        protected void griddata_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            griddata.PageIndex = e.NewPageIndex;
            GridDataBind();
        }


        //***************** This is function to handle page when Row Deleting  ***************************
        //-**************************************************************************

        protected void griddata_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                griddata.SelectedIndex = e.RowIndex;

                long CID = Int32.Parse(griddata.SelectedDataKey.Value.ToString());
                Boolean successadd = FileOrder.Delete(CID);
                if (successadd == true)
                {
                    GridDataBind();
                    lblMessage.Visible = true;
                    lblMessage.Text = "Record(s) was deleted successfully";

                }
            }
            catch (Exception)
            {
                lblMessage.Text = "Record(s) cannot be deleted, please contact your administrator";

            }

        }


        //***************** This is function to handle page when Row Data Bound  ***************************
        //-**************************************************************************
        protected void griddata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string GenderId;
            string birthdatevalue;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton LB = (LinkButton)e.Row.FindControl("LinkButton1");
                LB.Attributes.Add("onclick", "javascript:return " +
                "confirm('Are you sure you want to delete record(s) ( " +
                DataBinder.Eval(e.Row.DataItem, "Id") + " ) ?')");

            }

            int i;
            for (i = 0; i < griddata.Rows.Count; i++)
            {


                CheckBox relatedchbox;
                relatedchbox = ((CheckBox)(griddata.Rows[i].FindControl("CheckBox1")));

                Label lblGenderId;
                lblGenderId = ((Label)(griddata.Rows[i].FindControl("lblGenderId")));
                GenderId = lblGenderId.Text;


                Label lblbd;
                lblbd = ((Label)(griddata.Rows[i].FindControl("lblbd")));
                birthdatevalue = lblbd.Text;



                if (GenderId == "" || birthdatevalue == "")
                {

                    relatedchbox.Checked = false;
                    relatedchbox.Enabled = false;


                }

                else
                {
                    relatedchbox.Checked = true;
                    relatedchbox.Enabled = true;
                }
            }


        }

        protected void griddata_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlbrows.Visible = false;
            pnldetails.Visible = true;
            DetailsView1bind();
        }

        protected void DetailsView1bind()
        {
            Hashtable SearchTable = new Hashtable();

            SearchTable.Add("Id", griddata.SelectedDataKey.Value.ToString());
            DetViewdata.DataSource = Student.All(SearchTable);
            DetViewdata.DataBind();
        }



        # endregion


        # region " Search *********************"




        //***************** This is function to search by  Get All btn ***************************
        //-**************************************************************************
        protected void btnGetAll_Click(object sender, EventArgs e)
        {

            InitializeControls();
            GridDataBind();
        }



        protected void btnSearch_Click(object sender, EventArgs e)
        {
            GridDataBind();
            try
            {
                calculatstudentaccept();
            }
            catch
            {
                return;
            }

        }


        protected void calculatstudentaccept()
        {
            if (ddlSearchGrade_ID.SelectedIndex > 0)
            {

                lblaccountnoofacceptstudent.Text = "";
                int gradcapacity = School.Common.Structure.GetGradeCapacity(long.Parse(ddlSearchGrade_ID.SelectedValue));
                int noofacceptstudents = School.Common.Structure.GetAcceptedStudentsByGrade(long.Parse(ddlSearchGrade_ID.SelectedValue));

                int finalresualt = gradcapacity - noofacceptstudents;
                lblaccountnoofacceptstudent.Visible = true;

                lblaccountnoofacceptstudent.Text = "العدد المتاح لهذا الصف =  " + finalresualt.ToString();


            }

            else
            {


                lblaccountnoofacceptstudent.Visible = false;

            }
        }
        # endregion



        protected void ddlSearchcampus_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlSearchcampus_Id.SelectedIndex > 0)
            {
                ddlSearchCertificate_Id.Items.Clear();
                ddlSearchStage_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();


                ddlSearchCertificate_Id.DataSource = School.Common.Structure.GetCertificatesByCampus(Convert.ToInt64(ddlSearchcampus_Id.SelectedValue));
                ddlSearchCertificate_Id.DataTextField = "Name";
                ddlSearchCertificate_Id.DataValueField = "Id";
                ddlSearchCertificate_Id.DataBind();
                ddlSearchCertificate_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

                ddlSearchCertificate_Id.Enabled = true;
                ddlSearchStage_Id.Enabled = false;
                ddlSearchGrade_ID.Enabled = false;

            }

            else
            {
                ddlSearchCertificate_Id.Items.Clear();
                ddlSearchStage_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchCertificate_Id.Enabled = false;
                ddlSearchStage_Id.Enabled = false;
                ddlSearchGrade_ID.Enabled = false;

            }
        }


        protected void rblRelatives_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblRelatives.SelectedIndex == 2)
            {
                pnl4.Visible = true;
            }
            else
            {
                pnl4.Visible = false;
            }

        }

        protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox1.Checked == true)
            {
                pnl2.Visible = true;
                rblRelatives.SelectedIndex = 0;
                pnl4.Visible = false;
            }
            else
            {
                pnl2.Visible = false;
                rblRelatives.SelectedIndex = -1;

            }
            InitializeRelControls();
        }

        protected void btntakeaction_Click(object sender, EventArgs e)
        {
            AcceptOfStudents();

        }


        protected void AcceptOfStudents()
        {


            int mycount = 0;
            int i;
            for (i = 0; (i <= (griddata.Rows.Count - 1)); i++)
            {
                CheckBox relatedchbox;
                relatedchbox = ((CheckBox)(griddata.Rows[i].FindControl("CheckBox1")));

                if ((relatedchbox.Checked == true))
                {

                    long SID;
                    long EID;

                    long CampusID;
                    long CerID;
                    long GradID;
                    long StageID;
                    int GenderId;
                    string GBirthDate;
                    String reg_number;
                    DateTime bddate;

                    mycount = mycount + 1;
                    Label lblmystudentid;
                    lblmystudentid = ((Label)(griddata.Rows[i].FindControl("lblStudent_Id")));
                    SID = Convert.ToInt64(lblmystudentid.Text);

                    Label lblCampus_Id;
                    lblCampus_Id = ((Label)(griddata.Rows[i].FindControl("lblCampus_Id")));
                    CampusID = lblCampus_Id.Text != "" ? long.Parse(lblCampus_Id.Text) : 0;



                    Label lblCertificate_Id;
                    lblCertificate_Id = ((Label)(griddata.Rows[i].FindControl("lblCertificate_Id")));
                    CerID = lblCertificate_Id.Text != "" ? long.Parse(lblCertificate_Id.Text) : 0;


                    Label lblStage_Id;
                    lblStage_Id = ((Label)(griddata.Rows[i].FindControl("lblStage_Id")));
                    StageID = lblStage_Id.Text != "" ? long.Parse(lblStage_Id.Text) : 0;




                    Label lblGrade_ID;
                    lblGrade_ID = ((Label)(griddata.Rows[i].FindControl("lblGrade_ID")));
                    GradID = lblGrade_ID.Text != "" ? long.Parse(lblGrade_ID.Text) : 0;



                    ORG_EductionalYear org = StudentTransaction.GetCurrentEducationalYear();
                    EID = org.Id;

                    Label lblGenderId;
                    lblGenderId = ((Label)(griddata.Rows[i].FindControl("lblGenderId")));
                    GenderId = lblGenderId.Text != "" ? int.Parse(lblGenderId.Text) : 0;


                    Label lblGregorianBirthDate;
                    lblGregorianBirthDate = ((Label)(griddata.Rows[i].FindControl("lblGregorianBirthDate")));
                    GBirthDate = lblGregorianBirthDate.Text;


                    Label lblbd;
                    lblbd = ((Label)(griddata.Rows[i].FindControl("lblbd")));
                    bddate = Convert.ToDateTime(lblbd.Text);

                    StudentTransaction.Add(new ADM_Student_Transaction()

                     {
                         Student_Id = SID,
                         Status_Id = 5,
                         EductionalYear_Id = EID,
                         Campus_Id = CampusID,
                         Certificate_Id = CerID,
                         Stage_Id = StageID,
                         Grad_Id = GradID,
                     }

                   );

                    long reqno = School.Common.Structure.GetReq_Number();


                    string campus_code = School.Organization.Campus.Single(CampusID).Code;
                    string certficat_code = School.Organization.Certificate.Single(CerID).Code;

                    reg_number = string.Format("{0:00}", campus_code) + string.Format("{0:00}", certficat_code) + GenderId.ToString() + bddate.ToString("ddMMyy") + reqno;


                    TE_Student mystudent = new TE_Student();
                    mystudent.Id = SID;
                    mystudent.RegistrationNumber = long.Parse(reg_number);
                    Student.UpdateRegNum(mystudent);
                    mystudent.Status_Id = 5;
                    Student.UpdateStatusId(mystudent);
                    griddata.Rows[i].Visible = false;
                    lblLoopRecordNo.Text = "عدد الطلاب الذين تم قيدهم بالنظام = " + mycount.ToString();

                }
            }


            lblMessage.Text = "لقد تمت عملية القبول بنجاح";


        }

        public string GetStudentAge(object SAge)
        {


            try
            {

                DateTime bd = Convert.ToDateTime(SAge.ToString());
                DateTime rd = new DateTime(DateTime.Now.Year, 10, 1);

                TimeSpan diff = rd - bd;


                DateTime Age = DateTime.MinValue + diff;

                int Years = Age.Year - 1;
                int Months = Age.Month - 1;
                int Days = Age.Day - 1;


                string age = "(" + Days.ToString() + ")" + " (" + Months.ToString() + ")" + " (" + Years.ToString() + ")";
                return age;


            }

            catch
            {

                return "رجاء ادخال تاريخ الميلاد بشكل صحيح";

            }



        }


        public string GetCerName(string cerid)
        {
            ORG_Certificate cer = Certificate.Single(long.Parse(cerid));

            return cer.Name;
        }


        public string GetStageName(string stageid)
        {
            ORG_Stage stage = Stage.Single(long.Parse(stageid));

            return stage.Name;
        }


        public string GetGradName(string gradeid)
        {
            ORG_Grade grade = Grade.Single(long.Parse(gradeid));

            return grade.Name;
        }


        public string GetGander(object ganderid)
        {
            try
            {

                SchoolEntities db = new SchoolEntities();
                int xx = int.Parse(ganderid.ToString());
                LU_Gender gander = db.LU_Gender.Single(x => x.Id == xx);

                return gander.Kind;
            }
            catch
            {


                return "لم يتم ادخال النوع";
            }
        }


        protected void ddlSearchCertificate_Id_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (ddlSearchCertificate_Id.SelectedIndex > 0)
            {
                ddlSearchStage_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();

                ddlSearchStage_Id.DataSource = School.Common.Structure.GetStagesByCertificate(Convert.ToInt64(ddlSearchCertificate_Id.SelectedValue));
                ddlSearchStage_Id.DataTextField = "Name";
                ddlSearchStage_Id.DataValueField = "id";
                ddlSearchStage_Id.DataBind();
                ddlSearchStage_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlSearchStage_Id.Enabled = true;
                ddlSearchGrade_ID.Enabled = false;


            }

            else
            {
                ddlSearchStage_Id.Items.Clear();
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchStage_Id.Enabled = false;
                ddlSearchGrade_ID.Enabled = false;
            }
        }

        protected void ddlSearchStage_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlSearchStage_Id.SelectedIndex > 0)
            {
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchGrade_ID.DataSource = School.Common.Structure.GetGradesByStage(Convert.ToInt64(ddlSearchStage_Id.SelectedValue));
                ddlSearchGrade_ID.DataTextField = "Name";
                ddlSearchGrade_ID.DataValueField = "id";
                ddlSearchGrade_ID.DataBind();
                ddlSearchGrade_ID.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlSearchGrade_ID.Enabled = true;
            }

            else
            {
                ddlSearchGrade_ID.Items.Clear();
                ddlSearchGrade_ID.Enabled = false;

            }
        }

        protected void btnBackTosearch_Click(object sender, EventArgs e)
        {
            pnlbrows.Visible = true;
            pnldetails.Visible = false;
        }





    }
}